package com.example.controller;

import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.AliSmsUtill;
import com.example.utils.NumUtli;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.DuplicateFormatFlagsException;

@CrossOrigin
@Slf4j
@RestController
public class WebController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    AliSmsUtill aliSmsUtill;

    @Autowired
    NumUtli numUtli;


    @PostMapping("/senrcode")
    public Result SenRCode(@RequestBody User user) {
        User user1=userService.getphone(user.getAccount());
        if(user1!=null){
            return Result.error("该手机号已注册！");
        }
        if(StringUtils.hasLength(user.getAccount())){
            if(user.getAccount().matches("^1[3-9][0-9]{9}")){
                //生成验证码
                String code= numUtli.CreCode(4);

                aliSmsUtill.sendSmsCode(user.getAccount(),code);

                return Result.success("请求成功");
            }
        }
        return Result.error("请检查你的手机号！");
    }
    @PostMapping("/user/register")
    public Result add(@RequestBody User user) {

        if(user.getPasswords().equals(user.getPasswordsOne())){
            if(numUtli.getCode().equals(user.getCode())){
                try {
                    userService.insertUser(user);

                    return Result.success(user);
                } catch (Exception e) {
                    if (e instanceof DuplicateFormatFlagsException) {
                        return Result.error("插入数据库错误");
                    } else {
                        return Result.error("系统错误");
                    }
                }
            }
        }else{
            return Result.error("两次密码不一致");
        }
        return Result.error("");
    }

}




